'''
Created on Jun 1, 2010

@author: roni
'''
import unittest
from experimentRunner import ExperimentRunner
from projectConstants import ProjectConstants
from ns2Scenario import Ns2Scenario
from traceParser import TraceParser
import os


class TraceParserTester(unittest.TestCase):
    TEMP_TRACE_FILE = "%s/TraceParserTester.trace.temp" % ProjectConstants.RESROUCE_DIR
    TEMP_SCENARIO_FILE = "%s/TraceParserTester.scenario.temp" % ProjectConstants.RESROUCE_DIR
    
    def setUp(self):
        self.runner = ExperimentRunner()
        self.parser = TraceParser()
        os.chdir("../")        


    def tearDown(self):
        os.chdir("./testing")
        self.runner = None
        self.parser = None


    def testParse(self):
        # Create test scenario
        scenario = Ns2Scenario()  
        num_of_nodes = 6
        for node in xrange(num_of_nodes):     
            scenario.add_node()
        scenario.add_edge(0,1)
        scenario.add_edge(1,3)
        scenario.add_edge(3,4)        
        scenario.add_edge(0,2)
        scenario.add_edge(2,5)
                        
        scenario.add_agent(0, 5)
        scenario.add_agent(0, 4)
        scenario.save(TraceParserTester.TEMP_SCENARIO_FILE)
        
        # Run the scenario
        self.runner.run_ns2(TraceParserTester.TEMP_SCENARIO_FILE, TraceParserTester.TEMP_TRACE_FILE)
        
        # Parse the resulting file
        flow_to_details = self.parser.parse(TraceParserTester.TEMP_TRACE_FILE)
        self.assertEquals(len(flow_to_details.keys()),2)
        
        # Assert source and destination
        flow_to_5 = flow_to_details[0]
        flow_to_4 = flow_to_details[1]
        self.assertEqual(flow_to_5.source,0)
        self.assertEqual(flow_to_4.source,0)
        
        # Swap if necessary
        if flow_to_4.target != 4:
            self.assertEqual(flow_to_4.target,5)
            self.assertEqual(flow_to_5.target,4)
            temp = flow_to_5
            flow_to_5 = flow_to_4
            flow_to_4 = temp
        else:
            self.assertEqual(flow_to_5.target,5)
        
        # Assert parsing result is correct
        path_4 = flow_to_4.path
        self.assertEqual(len(path_4),4)
        self.assertEqual(path_4[0],0)
        self.assertEqual(path_4[1],1)
        self.assertEqual(path_4[2],3)
        self.assertEqual(path_4[3],4)
        
        path_5 = flow_to_5.path
        self.assertEqual(len(path_5),3)
        self.assertEqual(path_5[0],0)
        self.assertEqual(path_5[1],2)
        self.assertEqual(path_5[2],5)
        

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testParse']
    unittest.main()